//
//  ST_UpdateUserInfoSelectOptionItemController.swift
//  BTVideo
//
//  Created by DouLei on 2019/8/3.
//  Copyright © 2019 DouLei. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import HandyJSON


class ST_UpdateUserInfoSelectOptionItemController: ST_UpdateUserInfoChildBaseController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
    title_nav_btn.setTitleForAllStates("选择"+info_model.summaryTitle)
     
        
        view.addSubview(collectionView)

        collectionView.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(own_navigation_bar.snp.bottom)
        }
        
        JVrequest(PH.fetchOptionTagsApi,parameters:["search_key":info_model.modifyKey], success: { (json) in
            
            if let list = [ModifyUserItemCellModel].deserialize(from: json["data"].rawString() ?? "") as? [ModifyUserItemCellModel]{
                
                
                var array = [ModifyUserItemCellModel]()
                
                for (idx,item) in list.enumerated(){
                    
                    if item.id == self.info_model.id{
                        var  a = item
                        a.isSelected = true
                        self.last_selected_index = idx
                        array.append(a)
                    }else{
                        array.append(item)
                    }
                }
                
               self.data_array = array
                
                self.collectionView.reloadData()
            }
            
        }) { (code, err) in
            
            print("0------,",err)
            
        }
        
    }
    
    var last_selected_index:Int?
    
    var data_array = [ModifyUserItemCellModel]()
    
    lazy var itemWidth:CGFloat = {
        return ScreenWidth
    }()
    
    lazy var itemHeight = 65.cgFloat
    
    lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = CGSize.init(width: itemWidth, height: itemHeight)
   
        layout.minimumLineSpacing = 0
        //        layout.minimumInteritemSpacing = 14
        
        let bottomEdge = iPhoneXSeries ? BTSafeAreaBottom + 30 : 20 + 20
        
        layout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: bottomEdge, right: 0)
        
        let collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
        
        collection.register(cellWithClass: ModifyUserItemCell.self)
        
        collection.delegate = self
        
        collection.dataSource = self
        
        collection.alwaysBounceVertical = true
        
        collection.backgroundColor = Color.white
        
        if #available(iOS 11.0, *) {
            collection.contentInsetAdjustmentBehavior = .never
        }
        return collection
    }()
    
    
    override func right_click() {
        
        guard let lastSelected = last_selected_index else {return}
        
            self.info_model.title = self.data_array[lastSelected].title
        
            self.info_model.id = self.data_array[lastSelected].id
        
            self.info_model.icon = self.data_array[lastSelected].icon
        
            self.update_value_closure?(info_model)

            self.goback_previous_controller()
    }

    

}


extension ST_UpdateUserInfoSelectOptionItemController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCell(withClass: ModifyUserItemCell.self, for: indexPath)
        
        cell.bind(model: data_array[indexPath.row])
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        if indexPath.row != last_selected_index{
            
            if let lastIdx = last_selected_index {
                
                self.data_array[lastIdx].isSelected = false
            }
            
            self.data_array[indexPath.row].isSelected = true
            
            last_selected_index = indexPath.row
            
            self.collectionView.reloadData()
        }

    }

}


class ModifyUserItemCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(info_label)
        info_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(25)
            make.centerY.equalToSuperview()
        }
        contentView.addSubview(selected_btn)
        selected_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalToSuperview()
        }
        
        let line = UIView()
        line.backgroundColor = Color.init(hex: 0xF2F4F7)
        contentView.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.equalTo(info_label).offset(-5)
            make.height.equalTo(1)
            make.right.bottom.equalToSuperview()
        }
        
    }
    
    
    lazy var info_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#333333")
        //        control.numberOfLines = 0
        control.textAlignment = .left
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)
        return control
    }()
    
    lazy var selected_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImageForAllStates(UIImage())
        
        control.setImageForAllStates(ST_ImageUtils.imageName("mycenter_icon_未选择")!)
        
        control.setImage(ST_ImageUtils.imageName("mycenter_icon_选择"), for: UIControl.State.selected)
        
        control.isUserInteractionEnabled = false
        
        return control
    }()
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func bind(model:ModifyUserItemCellModel)  {
        
        info_label.text = model.title
        selected_btn.isSelected = model.isSelected
        
    }
    
    func bind(model:PinterestOptionCellModel)  {
        
        info_label.text = model.desc
        selected_btn.isSelected = model.isSelected
        
    }
    
    
}


struct ModifyUserItemCellModel:HandyJSON {
    
    init() {
    }
    
    var id:String = ""
    var title:String = ""
    var isSelected:Bool = false
    var icon:String = ""
}
